package epam.bookShelf.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.apache.log4j.Logger;

import epam.bookShelf.actors.Reader;
import epam.bookShelf.bookStuff.Author;

public class ReaderDAO {
	Logger log = null;
	
	private BookShelfDAO dao;
	
	//Name of Author table
    public static final String TABLE_NAME = "reader";
    
    //Names of columns
    public static final String LOGIN 	 = "login";
    public static final String PASS 	 = "pass";
    public static final String REAL_NAME = "real_name";
    public static final String PRIVACY 	 = "privacy";
    public static final String LIBRARY 	 = "lib";
	
	public ReaderDAO(BookShelfDAO dao) {
		this.dao = dao;
		
		Logger.getLogger(ReaderDAO.class);
	}
	
	/**
	 * Write Reader to DB
	 * @param author	reader instance
	 * @throws SQLException	problems with DB
	 */
	public void writeReader(Reader reader) throws SQLException {
        Connection conn = null;
        PreparedStatement prepStat = null;
        
        try {
            conn = dao.getConnection();
            prepStat = conn.prepareStatement(
                    "INSERT INTO " + TABLE_NAME + " (" 
                    + LOGIN 	+ ","
                    + PASS 		+ ","
                    + REAL_NAME + ","
                    + PRIVACY 	+ 
                    ") VALUES (?, ?, ?, ?);");
            
            fillReaderFields(reader, prepStat);
            
            prepStat.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("SQL error");
        } finally {
            dao.closeStatement(prepStat);
            dao.closeConnection(conn);
        }
	}
	
    /**
     * Get reader by login. Value of column login is unique, so in query result - 0 or 
     * 1 author 
     * @param name	readers login
     * @return	reader with proper login or null
     */
    public Reader readReader(String login) {    	
        Connection conn = null;
        PreparedStatement prepStat = null;
        
        Reader rez = null;
        
        try {
            conn = dao.getConnection();
            prepStat = conn.prepareStatement(
                    "SELECT * FROM " + TABLE_NAME + " WHERE "
                    + LOGIN + " = ?;");
            
            prepStat.setString(1, login);
            ResultSet resultSet = prepStat.executeQuery();            
            
            while (resultSet.next()) {
            	rez = parseReaderFromRezSet(resultSet);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            log.error("SQL error while book reading");
        } finally {
        	dao.closeStatement(prepStat);
        	dao.closeConnection(conn);             
        }
        
        return rez;
    }
	    
    public void updateReader(Author author) throws SQLException {
        //TODO
    	/*
    	Connection conn = null;
        PreparedStatement prepStat = null;
        
        try {
            conn = dao.getConnection();
            prepStat = conn.prepareStatement(
                    "UPDATE " + TABLE_NAME + " SET " 
                    + NAME + " = ?,"
                    + INFO + " = ?"
                    + " WHERE " + ID + " = ?;");
            
            fillAuthorFields(author, prepStat);
            
            prepStat.setLong(3, author.getId());
            
            prepStat.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            log.error("SQL error while author updating");
        } finally {
            dao.closeStatement(prepStat);
            dao.closeConnection(conn);
        }
        */
    }
    
    public void deleteReader(String login) throws SQLException {
    	Connection conn = null;
        PreparedStatement prepStat = null;
        
        try {
            conn = dao.getConnection();
            prepStat = conn.prepareStatement(
                    "DELETE FROM " + TABLE_NAME + " WHERE " 
                    + LOGIN + " = ?;");
            
            prepStat.setString(1, login);
            prepStat.executeUpdate();            
        } catch (SQLException e) {
            e.printStackTrace();
            log.error("SQL error while reader deleating");
        } finally {
        	dao.closeStatement(prepStat);
        	dao.closeConnection(conn);             
        }
    }
    
    private Reader parseReaderFromRezSet(ResultSet resultSet) throws SQLException {    	
        String login 	= resultSet.getString(LOGIN);        
        String pass 	= resultSet.getString(PASS);
        int privacy 	=  Integer.valueOf(resultSet.getString(PRIVACY));
        
        Reader reader = new Reader(login, pass);
        reader.setPrivacy(privacy);
        
        //TODO all other fields
    	
    	return reader;
    }
    
	
	private void fillReaderFields(Reader reader, PreparedStatement stat) {
		try {
			stat.setString(1, reader.getLogin());
			stat.setString(2, reader.getPass());
			
			if (reader.getRealName() != null) {
				stat.setString(3, reader.getRealName());
			} else {
				stat.setNull(3, Types.VARCHAR);
			}
			
			stat.setInt(4, reader.getPrivacy());
			
			//TODO: Work with library		
		} catch (SQLException e) {
			e.printStackTrace();
			log.error("Error while filleng author fields");
		}		
	}
}
